/*
 * Copyright (C) The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hpe.aruba.CPPM;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Rect;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.MultiDetector;
import com.google.android.gms.vision.MultiProcessor;
import com.google.android.gms.vision.barcode.BarcodeDetector;
import com.google.android.gms.vision.text.TextRecognizer;
import com.google.android.material.snackbar.Snackbar;
import com.hpe.aruba.CPPM.adapter.SwipeListAdapter;
import com.hpe.aruba.CPPM.camera.CameraSource;
import com.hpe.aruba.CPPM.camera.CameraSourcePreview;
import com.hpe.aruba.CPPM.camera.GraphicOverlay;
import com.hpe.aruba.CPPM.objects.Device;
import com.hpe.aruba.CPPM.objects.Role;
import com.hpe.aruba.CPPM.utils.ClearpassUtils;
import com.hpe.aruba.CPPM.utils.MacAdressUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

//import com.google.android.gms.vision.CameraSource;


/**
 * Activity for the multi-tracker app.  This app detects faces and barcodes with the rear facing
 * camera, and draws overlay graphics to indicate the position, size, and ID of each face and
 * barcode.
 */
public final class MultiTrackerActivity extends AppCompatActivity implements GraphicTracker.BarcodeUpdateListener, RecyclerItemTouchHelper.RecyclerItemTouchHelperListener {
    private static final String TAG = "MultiTracker";

    private static final int RC_HANDLE_GMS = 9001;
    // permission request codes need to be < 256
    private static final int RC_HANDLE_CAMERA_PERM = 2;
    private static final int MIN_OCCURS_READ = 10;
    private static final String DEVICES = "com.hpe.aruba.CPPM.DEVICES";

    private CameraSource mCameraSource = null;
    private CameraSourcePreview mPreview;
    private GraphicOverlay mGraphicOverlay;

    // Helper objects for detecting taps and pinches.
    private GestureDetector gestureDetector;
    private ScaleGestureDetector scaleGestureDetector;

    public Context mContext;

    private ArrayList<Device> macs;
    private SwipeListAdapter macListAdapter;
    private ArrayList<Device> macList;
    private TextView mItemCount;
    private RequestQueue queue;
    private List<Device> removedMacs;
    private Spinner spinner;
    private ClearpassUtils clearpassUtils;
    private View mTopLayout;

    /**
     * Initializes the UI and creates the detector pipeline.
     */
    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.main);

        mPreview = findViewById(R.id.preview);
        mGraphicOverlay = findViewById(R.id.faceOverlay);
        RecyclerView mMacListView = findViewById(R.id.macListView);
        mTopLayout = findViewById(R.id.topLayout);
        mItemCount = findViewById(R.id.itemCount);

        // read parameters from the intent used to launch the activity.
        // Check for the camera permission before accessing the camera.  If the
        // permission is not granted yet, request permission.
        int rc = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
        if (rc == PackageManager.PERMISSION_GRANTED) {
            createCameraSource(true, false);
        } else {
            requestCameraPermission();
        }

        gestureDetector = new GestureDetector(this, new CaptureGestureListener());
        scaleGestureDetector = new ScaleGestureDetector(this, new ScaleListener());

        queue = Volley.newRequestQueue(this);
//        if (bundle != null) {
//            macs = (ArrayList<Device>) bundle.getSerializable("macs");
//            macList = (ArrayList<Device>) bundle.getSerializable("macList");
//        } else {
        Intent intent = getIntent();
        macs = intent.getParcelableArrayListExtra(DEVICES);
        macList = new ArrayList<>();
        removedMacs = new ArrayList<>();
//        }
        macListAdapter = new SwipeListAdapter(this, macs, null);

//        macs.add(new Device("2E-94-E3-12-39-2D", "vendor1"));
//        macs.add(new Device("24-CE-36-EE-4D-CB", "sampleVendor"));
//        macs.add(new Device("2F-94-E3-12-39-2D", "vendor1"));
//        macs.add(new Device("34-CE-36-EE-4D-CB", "sampleVendor2"));
//        macs.add(new Device("16-97-E3-12-39-2D", "vendor2"));
//        macs.add(new Device("24-CA-36-EE-4D-CB", "2sampleVendor"));
//        macs.add(new Device("2E-99-E3-12-39-2D", "Vendor"));
//        macs.add(new Device("24-CE-47-EE-4D-CB", "Sample Vendor"));
//        macs.add(new Device("2E-95-E3-12-39-2D", "vendor 1"));
//        macs.add(new Device("94-CE-36-EE-4D-CB", "SampleVendor"));

        clearpassUtils = new ClearpassUtils(queue);

        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
        mMacListView.setLayoutManager(mLayoutManager);
        mMacListView.setItemAnimator(new DefaultItemAnimator());
        mMacListView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        mMacListView.setAdapter(macListAdapter);

        // adding item touch helper
        // only ItemTouchHelper.LEFT added to detect Right to Left swipe
        // if you want both Right -> Left and Left -> Right
        // add pass ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT as param
        ItemTouchHelper.SimpleCallback itemTouchHelperCallback = new RecyclerItemTouchHelper(0, ItemTouchHelper.LEFT, this);
        new ItemTouchHelper(itemTouchHelperCallback).attachToRecyclerView(mMacListView);

        Rect r = new Rect();
        mPreview.getWindowVisibleDisplayFrame(r);
        int[] i = new int[2];
        mPreview.getLocationInWindow(i);

        mGraphicOverlay.paintRect(r);

        spinner = findViewById(R.id.role);

        if (Data.roles != null) {
            ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item, Data.roles);
            adapter.setDropDownViewResource(android.R.layout
                    .simple_spinner_dropdown_item);
            spinner.setAdapter(adapter);
        }
    }

    public void processMacs(List<Device> macs) {
        for (Device mac : macs) {
            addMac(mac);
        }
        macListAdapter.notifyDataSetChanged();
    }

    private void addMac(Device mac) {
        if (contains(removedMacs, mac)) {
            return;
        }
        Optional<Device> macAddress = macList.stream().filter(m -> m.getMac().equals(mac.getMac())).findAny();
        if (macAddress.isPresent()) {
            macAddress.get().occurrenceFound();
            if (macAddress.get().getOccurrences() > MIN_OCCURS_READ && !contains(macs, mac)) {
                MacAdressUtils.getVendorAsync(queue, mac, r -> {
                    mac.setVendor(r);
                    macListAdapter.notifyDataSetChanged();
                }, m -> removeMac(mac));

                Role role = (Role) spinner.getSelectedItem();
                mac.setRole_id(role.getId());
                mac.setRole_name(role.getName());
                mac.setImported(false);
                macs.add(0, mac);
                updateCount();
                vibrate(100);
                macList = new ArrayList<>();
            }
        } else {
            macList.add(mac);
        }
    }

    private void removeMac(Device mac) {
        macList.remove(mac);
        macs.remove(mac);
        removedMacs.add(mac);
        updateCount();
        macListAdapter.notifyDataSetChanged();
    }

    private void updateCount() {
        String countText = getString(R.string.count) + macs.size();
        mItemCount.setText(countText);
    }

    public void processMac(Device mac) {
//        macListAdapter.setCurrentMacs(currentMacs);
        addMac(mac);
        macListAdapter.notifyDataSetChanged();
    }

    private boolean contains(List<Device> macs, Device text) {
        return macs.stream().anyMatch(mac -> mac.getMac().equals(text.getMac()));
    }

    protected void onSaveInstanceState(@NonNull Bundle extra) {
        super.onSaveInstanceState(extra);

        extra.putSerializable("macs", macs);
        extra.putSerializable("macList", macList);

    }

    public void uploadAdresses(View view) {
        Intent returnIntent = new Intent();
        returnIntent.putExtra(DEVICES, macs);
        setResult(Activity.RESULT_OK, returnIntent);
        finish();
    }

    public boolean isMacAdded(Device text) {
        return contains(macs, text);
    }

    private class CaptureGestureListener extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onSingleTapConfirmed(MotionEvent e) {
            return onTap(e.getRawX(), e.getRawY()) || super.onSingleTapConfirmed(e);
            //return true;
        }
    }

    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction, int position) {
        if (viewHolder instanceof SwipeListAdapter.MyViewHolder) {
            // get the removed item name to display it in snack bar
            Device device = macs.get(viewHolder.getAdapterPosition());

            // backup of removed item for undo purpose
            final Device deletedItem = macs.get(viewHolder.getAdapterPosition());
            final int deletedIndex = viewHolder.getAdapterPosition();

            // remove the item from recycler view
            macListAdapter.removeItem(viewHolder.getAdapterPosition());
//            updateCount();

            if (device.isImported()) {
                AlertDialog confirmationDialogBox = new AlertDialog.Builder(this)
                        .setTitle("Delete")
                        .setMessage("Do you want to Delete")
//                    .setIcon(R.drawable.delete)

                        .setPositiveButton("Delete", (dialog, whichButton) -> {
                            clearpassUtils.deleteDevice(device);
                            dialog.dismiss();
                        })
                        .setNegativeButton("cancel", (dialog, which) -> {
                            macListAdapter.restoreItem(deletedItem, deletedIndex);
                            dialog.dismiss();
                        })
                        .create();
                confirmationDialogBox.show();
            } else {
                // showing snack bar with Undo option
                Snackbar snackbar = Snackbar
                        .make(mTopLayout, device.getMac() + getString(R.string.removed), Snackbar.LENGTH_LONG);
                snackbar.setAction("UNDO", view -> {
                    // undo is selected, restore the deleted item
                    macListAdapter.restoreItem(deletedItem, deletedIndex);
                });
                snackbar.setActionTextColor(getColor(R.color.aruba_orange));
                snackbar.show();
            }
        }
    }

    private class ScaleListener implements ScaleGestureDetector.OnScaleGestureListener {

        /**
         * Responds to scaling events for a gesture in progress.
         * Reported by pointer motion.
         *
         * @param detector The detector reporting the event - use this to
         *                 retrieve extended info about event state.
         * @return Whether or not the detector should consider this event
         * as handled. If an event was not handled, the detector
         * will continue to accumulate movement until an event is
         * handled. This can be useful if an application, for example,
         * only wants to update scaling factors if the change is
         * greater than 0.01.
         */
        @Override
        public boolean onScale(ScaleGestureDetector detector) {
            return false;
        }

        /**
         * Responds to the beginning of a scaling gesture. Reported by
         * new pointers going down.
         *
         * @param detector The detector reporting the event - use this to
         *                 retrieve extended info about event state.
         * @return Whether or not the detector should continue recognizing
         * this gesture. For example, if a gesture is beginning
         * with a focal point outside of a region where it makes
         * sense, onScaleBegin() may return false to ignore the
         * rest of the gesture.
         */
        @Override
        public boolean onScaleBegin(ScaleGestureDetector detector) {
            return true;
        }

        /**
         * Responds to the end of a scale gesture. Reported by existing
         * pointers going up.
         * <p/>
         * Once a scale has ended, {@link ScaleGestureDetector#getFocusX()}
         * and {@link ScaleGestureDetector#getFocusY()} will return focal point
         * of the pointers remaining on the screen.
         *
         * @param detector The detector reporting the event - use this to
         *                 retrieve extended info about event state.
         */
        @Override
        public void onScaleEnd(ScaleGestureDetector detector) {
            mCameraSource.doZoom(detector.getScaleFactor());
        }
    }

    /**
     * onTap returns the tapped barcode result to the calling Activity.
     *
     * @param rawX - the raw position of the tap
     * @param rawY - the raw position of the tap.
     * @return true if the activity is ending.
     */
    private boolean onTap(float rawX, float rawY) {

        // Find tap point in preview frame coordinates.
        return true;
    }

    @Override
    public boolean onTouchEvent(MotionEvent e) {
        boolean b = scaleGestureDetector.onTouchEvent(e);
        boolean c = gestureDetector.onTouchEvent(e);

        return b || c || super.onTouchEvent(e);
    }

    /**
     * Handles the requesting of the camera permission.  This includes
     * showing a "Snackbar" message of why the permission is needed then
     * sending the request.
     */
    private void requestCameraPermission() {
        Log.w(TAG, "Camera permission is not granted. Requesting permission");

        final String[] permissions = new String[]{Manifest.permission.CAMERA};

        if (!ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.CAMERA)) {
            ActivityCompat.requestPermissions(this, permissions, RC_HANDLE_CAMERA_PERM);
            return;
        }

        final Activity thisActivity = this;

        View.OnClickListener listener = view -> ActivityCompat.requestPermissions(thisActivity, permissions,
                RC_HANDLE_CAMERA_PERM);

        Snackbar.make(mGraphicOverlay, R.string.permission_camera_rationale,
                Snackbar.LENGTH_INDEFINITE)
                .setAction(R.string.ok, listener)
                .show();
    }


    /**
     * Creates and starts the camera.  Note that this uses a higher resolution in comparison
     * to other detection examples to enable the barcode detector to detect small barcodes
     * at long distances.
     */
    private void createCameraSource(boolean autoFocus, boolean useFlash) {
        Context context = getApplicationContext();
        mContext = context;

        // A barcode detector is created to track barcodes.  An associated multi-processor instance
        // is set to receive the barcode detection results, track the barcodes, and maintain
        // graphics for each barcode on screen.  The factory is used by the multi-processor to
        // create a separate tracker instance for each barcode.
        BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(context).build();
        BarcodeTrackerFactory barcodeFactory = new BarcodeTrackerFactory(mGraphicOverlay, this);
        barcodeDetector.setProcessor(
                new MultiProcessor.Builder<>(barcodeFactory).build());

        // A text detector is created to track text OCR.  An associated multi-processor instance
        // is set to receive the barcode detection results, track the text OCR, and maintain
        // graphics for each text OCR on screen.  The factory is used by the multi-processor to
        // create a separate tracker instance for each text OCR.
        TextRecognizer textRecognizer = new TextRecognizer.Builder(context).build();
        OcrTrackerFactory ocrTrackerFactory = new OcrTrackerFactory(mGraphicOverlay, this);
        textRecognizer.setProcessor(
                new MultiProcessor.Builder<>(ocrTrackerFactory).build());


        // A multi-detector groups the two detectors together as one detector.  All images received
        // by this detector from the camera will be sent to each of the underlying detectors, which
        // will each do face and barcode detection, respectively.  The detection results from each
        // are then sent to associated tracker instances which maintain per-item graphics on the
        // screen.
        MultiDetector multiDetector = new MultiDetector.Builder()
                //.add(faceDetector)
                .add(barcodeDetector)
                .add(textRecognizer)
                .build();

        if (!multiDetector.isOperational()) {
            // Note: The first time that an app using the barcode or face API is installed on a
            // device, GMS will download a native libraries to the device in order to do detection.
            // Usually this completes before the app is run for the first time.  But if that
            // download has not yet completed, then the above call will not detect any barcodes
            // and/or faces.
            //
            // isOperational() can be used to check if the required native libraries are currently
            // available.  The detectors will automatically become operational once the library
            // downloads complete on device.
            Log.w(TAG, "Detector dependencies are not yet available.");

            // Check for low storage.  If there is low storage, the native library will not be
            // downloaded, so detection will not become operational.
            IntentFilter lowstorageFilter = new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW);
            boolean hasLowStorage = registerReceiver(null, lowstorageFilter) != null;

            if (hasLowStorage) {
                Toast.makeText(this, R.string.low_storage_error, Toast.LENGTH_LONG).show();
                Log.w(TAG, getString(R.string.low_storage_error));
            }
        }

        // Creates and starts the camera.  Note that this uses a higher resolution in comparison
        // to other detection examples to enable the barcode detector to detect small barcodes
        // at long distances.
        mCameraSource = new CameraSource.Builder(getApplicationContext(), multiDetector)
                .setFacing(CameraSource.CAMERA_FACING_BACK)
//                .setRequestedPreviewSize(1280, 512)
                .setFocusMode(autoFocus ? Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE : null)
                .setFlashMode(useFlash ? Camera.Parameters.FLASH_MODE_ON : Camera.Parameters.FLASH_MODE_OFF)
                //.setRequestedFps(15.0f)
                .setRequestedFps(5.0f)
                .build();
    }

    /**
     * Restarts the camera.
     */
    @Override
    protected void onResume() {
        super.onResume();

        // Check for the camera permission before accessing the camera.  If the
        // permission is not granted yet, request permission.
        int rc = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
        if (rc == PackageManager.PERMISSION_GRANTED) {
            createCameraSource(true, true);

            startCameraSource();
        } else {
            requestCameraPermission();
        }
    }

    /**
     * Stops the camera.
     */
    @Override
    protected void onPause() {
        super.onPause();
        mPreview.stop();
    }

    /**
     * Releases the resources associated with the camera source, the associated detectors, and the
     * rest of the processing pipeline.
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
//        if (mCameraSource != null) {
//            //mCameraSource.release();
//        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mCameraSource != null) {
            mCameraSource.release();
        }
    }


    /**
     * Callback for the result from requesting permissions. This method
     * is invoked for every call on {@link #requestPermissions(String[], int)}.
     * <p>
     * <strong>Note:</strong> It is possible that the permissions request interaction
     * with the user is interrupted. In this case you will receive empty permissions
     * and results arrays which should be treated as a cancellation.
     * </p>
     *
     * @param requestCode  The request code passed in {@link #requestPermissions(String[], int)}.
     * @param permissions  The requested permissions. Never null.
     * @param grantResults The grant results for the corresponding permissions
     *                     which is either {@link PackageManager#PERMISSION_GRANTED}
     *                     or {@link PackageManager#PERMISSION_DENIED}. Never null.
     * @see #requestPermissions(String[], int)
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode != RC_HANDLE_CAMERA_PERM) {
            Log.d(TAG, "Got unexpected permission result: " + requestCode);
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            return;
        }

        if (grantResults.length != 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            Log.d(TAG, "Camera permission granted - initialize the camera source");
            // we have permission, so create the camerasource
            boolean autoFocus = true;
            boolean useFlash = false;
            createCameraSource(autoFocus, useFlash);
            return;
        }

        Log.e(TAG, "Permission not granted: results len = " + grantResults.length +
                " Result code = " + (grantResults.length > 0 ? grantResults[0] : "(empty)"));

        DialogInterface.OnClickListener listener = (dialog, id) -> finish();

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Multitracker sample")
                .setMessage(R.string.no_camera_permission)
                .setPositiveButton(R.string.ok, listener)
                .show();
    }

    /**
     * Starts or restarts the camera source, if it exists.  If the camera source doesn't exist yet
     * (e.g., because onResume was called before the camera source was created), this will be called
     * again when the camera source is created.
     */
    @SuppressLint("MissingPermission")
    private void startCameraSource() {

        // check that the device has play services available.
        int code = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(
                getApplicationContext());
        if (code != ConnectionResult.SUCCESS) {
            Dialog dlg =
                    GoogleApiAvailability.getInstance().getErrorDialog(this, code, RC_HANDLE_GMS);
            dlg.show();
        }

        if (mCameraSource != null) {
            try {
                mPreview.start(mCameraSource, mGraphicOverlay);
            } catch (IOException e) {
                Log.e(TAG, "Unable to start camera source.", e);
                mCameraSource.release();
                mCameraSource = null;
            }
        }
    }

    @Override
    public void onBarcodeDetected(Detector.Detections detectionResults, boolean flag) {

//        if (flag) { //TextBlock
//            final SparseArray items = detectionResults.getDetectedItems();
//            for (int i = 0; i < items.size(); ++i) {
//                TextBlock item = (TextBlock) items.valueAt(i);
//                TextValue = item.getValue();
//            }

//        } else { //Barcode
//            final SparseArray items = detectionResults.getDetectedItems();
//            Barcode barcode = (Barcode) items.valueAt(0);
//        }
    }

    private void vibrate(long ms) {
        Vibrator vibrator = (Vibrator) mContext.getSystemService(VIBRATOR_SERVICE);
        if (Build.VERSION.SDK_INT >= 26) {
            if (vibrator != null) {
                vibrator.vibrate(VibrationEffect.createOneShot(ms, VibrationEffect.DEFAULT_AMPLITUDE));
            }
        } else {
            if (vibrator != null) {
                vibrator.vibrate(ms);
            }
        }
    }
}
